/**
 * 更新导航栏的认证状态
 */
function updateAuthNav() {
    $.ajax({        url: '/api/users/current',
        type: 'GET',
        timeout: 5000,
        success: function(user) {
            console.log('updateAuthNav success, user:', user);
            
            // 检查是否收到了HTML响应（被重定向到登录页）
            if (typeof user === 'string' && user.includes("<!DOCTYPE html>")) {
                console.log('updateAuthNav: Received HTML response - user not authenticated');
                $('#authNav').html(getLoginRegisterNavHtml());
                return;
            }
            
            // 检查用户对象和基本字段是否有效
            if (user && user.userRole && (user.username || user.realName)) {
                let displayName = user.realName || user.username;
                let html = `
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user me-1"></i>${displayName}
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="/user/profile">个人信息</a></li>
                            <li><a class="dropdown-item" href="/user/tickets">我的车票</a></li>
                `;

                if (user.userRole === 'ADMIN') {
                    html += `<li><a class="dropdown-item" href="/admin/dashboard">管理后台</a></li>`;
                }

                html += `
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="#" id="logoutBtn">退出登录</a></li>
                        </ul>
                    </li>
                `;
                $('#authNav').html(html);

                $('#logoutBtn').on('click', function(e) {
                    e.preventDefault();
                    logout();
                });
            } else {
                console.log('Invalid user object for nav, showing login/register. User:', user);
                $('#authNav').html(getLoginRegisterNavHtml());
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log('updateAuthNav error - Status:', jqXHR.status, 'Text:', textStatus, 'Error:', errorThrown);
            console.log('Response text:', jqXHR.responseText);
            // 所有错误情况都显示登录注册链接
            $('#authNav').html(getLoginRegisterNavHtml());
        }
    });
}

/**
 * 获取当前用户
 * @returns {Promise} 返回用户信息的Promise
 */
function getCurrentUser() {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: '/api/users/current',
            type: 'GET',
            timeout: 5000,success: function(user) {
                // 检查是否收到了HTML响应（被重定向到登录页）
                if (typeof user === 'string' && user.includes("<!DOCTYPE html>")) {
                    console.log('getCurrentUser: Received HTML response - user not authenticated');
                    reject(new Error('User not authenticated'));
                    return;
                }
                
                // 检查用户对象的有效性
                if (user && user.userRole && (user.username || user.realName)) {
                    resolve(user);
                } else {
                    console.log('getCurrentUser: Invalid user object received:', user);
                    reject(new Error('Invalid user object'));
                }
            },error: function(jqXHR, textStatus, errorThrown) {
                console.log("getCurrentUser AJAX Error:", textStatus, errorThrown);
                console.log("Status Code:", jqXHR.status);
                
                // 如果是200状态码但返回HTML（被重定向到登录页），说明用户未登录
                if (jqXHR.status === 200 && jqXHR.responseText && jqXHR.responseText.includes("<!DOCTYPE html>")) {
                    console.log("User not authenticated - redirected to login page");
                    reject(new Error('User not authenticated'));
                } else {
                    console.log("Response Text:", jqXHR.responseText);
                    reject({
                        status: jqXHR.status,
                        statusText: textStatus,
                        error: errorThrown,
                        responseText: jqXHR.responseText
                    });
                }
            }
        });
    });
}

// Helper function to generate HTML for login/register buttons
function getLoginRegisterButtonsHtml() {
    return `
        <a href="/custom-login" class="btn btn-primary btn-lg me-3">
            <i class="fas fa-sign-in-alt me-1"></i>立即登录
        </a>
        <a href="/register" class="btn btn-outline-primary btn-lg">
            <i class="fas fa-user-plus me-1"></i>注册账号
        </a>
    `;
}

// Helper function to generate HTML for login/register nav link
function getLoginRegisterNavHtml() {
    return `
        <li class="nav-item">
            <span class="nav-link">
                <a href="/custom-login" class="text-decoration-none text-light">
                    <i class="fas fa-sign-in-alt me-1"></i>登录
                </a>
                <span class="text-light mx-1">|</span>
                <a href="/register" class="text-decoration-none text-light">
                    <i class="fas fa-user-plus me-1"></i>注册
                </a>
            </span>
        </li>
    `;
}

/**
 * 更新首页主要内容区域的认证状态
 */
function updateAuthButtons() {
    const authButtonsElement = $('#authButtons');
    
    console.log('authButtons element found:', authButtonsElement.length > 0);
    
    if (authButtonsElement.length === 0) {
        console.log('No authButtons element found, skipping update');
        return;
    }
    
    // 显示加载状态
    authButtonsElement.html('<div class="text-center"><i class="fas fa-spinner fa-spin"></i> 加载中...</div>');
      // 直接使用 $.ajax 而不是 Promise 包装，确保更好的错误处理
    $.ajax({
        url: '/api/users/current',
        type: 'GET',
        timeout: 5000,
        success: function(user) {
            console.log('updateAuthButtons success, user:', user);
            
            // 检查是否收到了HTML响应（被重定向到登录页）
            if (typeof user === 'string' && user.includes("<!DOCTYPE html>")) {
                console.log('updateAuthButtons: Received HTML response - user not authenticated');
                authButtonsElement.html(getLoginRegisterButtonsHtml());
                return;
            }
            
            // 检查用户对象和角色是否有效
            if (user && user.userRole && (user.username || user.realName)) {
                if (user.userRole === 'USER') {
                    let welcomeHtml = `
                        <div class="alert alert-success" role="alert">
                            <i class="fas fa-user-check me-2"></i>
                            欢迎回来，<strong>${user.realName || user.username}</strong>！
                        </div>
                        <p class="text-muted">您可以开始使用系统的各项功能</p>
                    `;
                    authButtonsElement.html(welcomeHtml);
                } else if (user.userRole === 'ADMIN') {
                    let adminHtml = `
                        <div class="alert alert-primary" role="alert">
                            <i class="fas fa-user-shield me-2"></i>
                            管理员，<strong>${user.realName || user.username}</strong>
                        </div>
                        <a href="/admin/dashboard" class="btn btn-primary btn-lg">
                            <i class="fas fa-tachometer-alt me-1"></i>进入管理后台
                        </a>
                    `;
                    authButtonsElement.html(adminHtml);
                } else {
                    console.log('Unknown user role:', user.userRole);
                    authButtonsElement.html(getLoginRegisterButtonsHtml());
                }
            } else {
                console.log('Invalid user object or missing essential fields:', user);
                authButtonsElement.html(getLoginRegisterButtonsHtml());
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log('updateAuthButtons error - Status:', jqXHR.status, 'Text:', textStatus, 'Error:', errorThrown);
            console.log('Response text:', jqXHR.responseText);
            // 所有错误情况都显示登录注册按钮
            authButtonsElement.html(getLoginRegisterButtonsHtml());
        }
    });
}

/**
 * 退出登录
 */
function logout() {
    $.ajax({
        url: '/logout',
        type: 'POST',
        success: function() {
            // 退出成功，重定向到首页
            window.location.href = '/';
        },
        error: function() {
            // 即使出错也重定向到首页
            window.location.href = '/';
        }
    });
}

/**
 * 检查用户认证状态并进行相应跳转
 * @param {string} targetUrl 目标页面URL
 * @param {string} loginRedirectUrl 如果未登录要跳转的登录页面URL（包含redirect参数）
 */
function checkAuthAndRedirect(targetUrl, loginRedirectUrl) {
    getCurrentUser().then(function(user) {
        // 用户已登录，直接跳转到目标页面
        window.location.href = targetUrl;
    }).catch(function() {
        // 用户未登录，跳转到登录页面
        window.location.href = loginRedirectUrl || `/custom-login?redirect=${encodeURIComponent(targetUrl)}`;
    });
}

/**
 * 直接跳转到指定页面（无需登录验证）
 * @param {string} url 目标页面URL
 */
function directRedirect(url) {
    window.location.href = url;
}